package com.rankeiot.core.util;

import com.rankeiot.core.data.response.Resp;
import lombok.Data;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;

/**
 * 前端进程,通过SSE来通知前端进度
 */
public class FrontendProcess {
    private SseEmitter emitter;

    private FrontendProcess() {
        this.emitter = new SseEmitter();
    }

    public SseEmitter getEmitter(){
        return emitter;
    }
    public static SseEmitter create(Consumer<FrontendProcess> task) {

        FrontendProcess process = new FrontendProcess();
        SseEmitter emitter = process.emitter;
        CompletableFuture.runAsync(() -> {
            try {
                task.accept(process);
                emitter.complete();
            }catch (Exception e){
                process.error(e.getMessage());
                emitter.completeWithError(e);
            }
        });
        return emitter;
    }
    public void error(String error){
        error(400,error);
    }
    public void error(int errorCode,String error){
        send("error",error,errorCode);
    }
    public void process(int percent){
       send("process",percent+"");
    }
    public void info(String info){
        send("info",info);
    }
    public void finish(String info){
        send("finish",info);
    }
    public void comment(String info){
       send("comment",info);
    }
    public void send(String type,String data){
        send(type,data,0);
    }
    public void send(String type,String data,int code){
        Info info=new Info();
        info.code=code;
        info.data=data;
        info.type=type;
        send(info);
    }
    public void send(Info info){
        send(JSONUtil.toJSONString(info));
    }
    public void send(String originMessage){
        try {
            emitter.send(originMessage);
        } catch (IOException e) {
            emitter.completeWithError(e);
        }
    }
    @Data
    public static class Info{
        int code = 0;
        String type;
        String data;
    }
}
